package cn.flyingocean.spider.impl.com.douban.book.com.douban.book;

import cn.flyingocean.spider.impl.com.douban.book.AbstractSpider;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import cn.flyingocean.spider.Spider;

import java.util.HashMap;
import java.util.Map;

/**
 * Spider 的示例实现，在test目录下有相应的测试类
 */
public class DoubanSpider extends AbstractSpider {

    private String url;

    public Object doWork(Document document) {
        return null;
    }

    public Object doWork(String url) {
        return null;
    }

    public Object doWork() {
        try {
            Document document = Jsoup.connect(this.getUrl()).timeout(99999).get();
            Element info = document.getElementById("info");
            Elements pls = info.select("span[class=pl]");
            // 返回的信息
            Map<String,String> r = new HashMap<String, String>();
            System.out.println(info.ownText());
            String[] strings = info.ownText().split(" ");
            // 获取作者名字
            String author = info.getElementsByTag("a").first().text();
            // 获取书名
            String bookName = document.getElementsByTag("h1").first().text();
            // 获取图书封面图片链接
            Element a = document.getElementsByClass("nbg").first();
            String[] strings1 = a.attr("href").split("/");
            r.put("图片名:", strings1[strings1.length-1]);
            r.put("书名:",bookName);
            r.put(pls.get(0).text(),author);
            for (int i=1;i<pls.size();i++){
                r.put(pls.get(i).text(),strings[i]);
            }
            return  r;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getUrl() {
        return url;
    }

    public void beforeDead() {
    }

    public Spider setUrl(String url){
        this.url = url;
        return this;
    }
}
